package com.yang.sso.oauth.oauth.exception;


import com.yang.sso.oauth.result.Result;
import com.yang.sso.oauth.enums.ResultCode;
import com.yang.sso.oauth.utils.jackson.JacksonUtil;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author lslands
 * @Version 1.0
 * @Date 2022/6/9 14:24
 * @PackageName:com.ami.security.handler
 * @ClassName: MyAccessDeniedHandler
 * @Description:    授权服务异常 --- 权限不足异常
 */
@Configuration
public class MyAccessDeniedHandler implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException, ServletException {
        //设置响应状态吗
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        response.setHeader("Content-Type","application/json;charset=uft-8");
        PrintWriter writer=response.getWriter();
        writer.write(JacksonUtil.bean2Json(Result.failed(ResultCode.ACCESS_UNAUTHORIZED)));
        writer.flush();
        writer.close();
    }
}
